# -*- coding:utf-8 -*-
import socket
import fcntl
import struct

__author__ = 'lu'
import os
import platform
import locale

my_platform = platform.system().lower()


def log(str):
    print("<<<%s>>> " % str)


# ubuntu server should install sudo apt-get install postfix
def mail(subject, content, to):
    cmd = 'echo \"%s\" | mail -t %s -s \'%s\'' % (content, to, subject)
    log('%s' % cmd)
    if 'linux' in my_platform:
        os.system(cmd)


def setlocale():
    language_code, encoding = locale.getdefaultlocale()
    if language_code is None:
        language_code = 'en_GB'
    if encoding is None:
        encoding = 'UTF-8'
    if encoding.lower() == 'utf':
        encoding = 'UTF-8'
    locale.setlocale(locale.LC_ALL, '%s.%s' % (language_code, encoding))


def execCmd(cmd):
    r = os.popen(cmd)
    text = r.read()
    r.close()
    return text


def get_ip_address(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    return socket.inet_ntoa(fcntl.ioctl(
        s.fileno(),
        0x8915,  # SIOCGIFADDR
        struct.pack('256s', ifname[:15]))
                            [20:24])
